package microservices

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"kuangstudy-mall/apis/order-web/global"
	"kuangstudy-mall/apis/order-web/proto"
)

func GetNacosOrderClient() proto.OrderClient {
	// nacos核心配置
	clientConfig := *constant.NewClientConfig(
		constant.WithNamespaceId("public"), //When namespace is public, fill in the blank string here.
		constant.WithTimeoutMs(10000),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir("d://tmp/nacos/log"),
		constant.WithUsername("nacos"),
		constant.WithPassword("nacos"),
		constant.WithCacheDir("d://tmp/nacos/cache"),
		constant.WithLogLevel("debug"),
	)

	// nacos服务配置
	serverConfigs := []constant.ServerConfig{
		*constant.NewServerConfig(
			"127.0.0.1",
			8848,
			constant.WithScheme("http"),
			constant.WithContextPath("/nacos"),
		),
	}

	// 获取操作的nacos服务的客户端对象
	// Another way of create naming client for service discovery (recommend)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)

	if err != nil {
		panic(err)
	}
	fmt.Println("global.ServerConfig.Name", global.ServerConfig.Name)
	instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: global.ServerConfig.Name,
		GroupName:   "DEFAULT_GROUP",     // default value is DEFAULT_GROUP
		Clusters:    []string{"DEFAULT"}, // default value is DEFAULT
	})

	fmt.Println(fmt.Sprintf("你调用的服务实例是：%s:%d", instance.Ip, instance.Port))
	conn, err := grpc.Dial(fmt.Sprintf("%s:%d", instance.Ip, instance.Port),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		panic(err)
	}

	return proto.NewOrderClient(conn)
}
